#include <jack/jack.h>
#include <jack/midiport.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

jack_client_t *client;
jack_port_t *output_port;
extern volatile unsigned short int pot_val[];
extern volatile unsigned short int jack_status;

static int process(jack_nframes_t nframes, void *arg)
{
        int i;
	void* port_buf = jack_port_get_buffer(output_port, nframes);
	unsigned char* buffer;
	jack_midi_clear_buffer(port_buf);
        buffer = jack_midi_event_reserve(port_buf, 0, 3);
	buffer[2] = ((pot_val[0])/2);
	buffer[1] = 40;
	buffer[0] = 176;
//	for(i=0; i<nframes; i++)
//	{
//       }
        buffer = jack_midi_event_reserve(port_buf, 1, 3);
	buffer[2] = ((pot_val[1])/2);
	buffer[1] = 41;
	buffer[0] = 176;        
	return 0;
}

void* start_jack(void* args){
        jack_nframes_t nframes;
        if((client = jack_client_open ("avrcpcs", JackNullOption, NULL)) == 0){
                fprintf (stderr, "jack server not running?\n");
                jack_status = 1;
        }
        jack_set_process_callback (client, process, 0);
        output_port = jack_port_register (client, "out", JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0);
//        nframes = jack_get_buffer_size(client);
        if (jack_activate(client))
	{
		fprintf (stderr, "cannot activate client");
                jack_status = 1;
	}

	while (1)
	{
		sleep(1);
	};
}